<?php

namespace App\Admin\Actions\Batch;

use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;
use App\Models\CabinetDataSecondBackup; 
use Chumper\Zipper\Zipper;

class DownloadCabinetSecondExcel extends BatchAction
{

    // 注意action的构造方法参数一定要给默认值
    public function __construct($title = null)
    {
        $this->title = $title;
    }

    // 确认弹窗信息
    public function confirm()
    {
        return '您确定要下载已选中的记录吗？';
    }

    // 处理请求
    public function handle(Request $request)
    {
        $folderName = date("YmdHis");
        $folder = public_path(CabinetDataSecondBackup::CATALOGUE).'/'.$folderName;
        $zip = $folder.'.zip';
        mkdir($folder);
        chmod($folder, 0777);

        $fileArr = [];

        // 获取选中的ID数组
        $keys = $this->getKey();

        foreach ($keys as $one) {
            $oneExcel = CabinetDataSecondBackup::find($one);
            $path = $folder.'/'.$oneExcel['date'];         
            if (!is_dir($path.'/')) {
                mkdir($path);
                chmod($path, 0777);
            }
            $oldFile = public_path(CabinetDataSecondBackup::CATALOGUE).'/'.$oneExcel['date'].'/'.$oneExcel['name'].'.csv';
            $newFile = $path.'/'.$oneExcel['name'].'.csv';
            exec('cp '.$oldFile.' '.$newFile);
        }


        $zipper = new Zipper();
        $zipper->make($zip)->folder($folderName)->add($folder)->close();;
        exec('rm -rf '.$folder);
        $url = url(CabinetDataSecondBackup::CATALOGUE.'/'.$folderName.'.zip');
        $message = '下载成功';

        return $this->response()->download($url);
    }
}